package com.foxit.pdf2html5.web.controller;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;







import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.foxit.pdf2html5.common.TaskStore;
//import com.foxit.pdf2html5.conver2bin.task.Conver2BinTask;
//import com.foxit.pdf2html5.demo.DemoDocument;
import com.foxit.pdf2html5.progressbar.FileUploadProgressListener;
import com.foxit.pdf2html5.progressbar.FileUploadStatus;
import com.foxit.pdf2html5.web.common.Config;
import com.foxit.pdf2html5.web.util.FoxitCloudUtils;
import com.google.gson.Gson;

@Controller
public class FileUploadController {
	protected static final Logger logger = Logger.getLogger(FileUploadController.class);

	private FileItem uploadFile;

	/**
	 * current HTTP request object.
	 */
	HttpServletRequest servletRequest;
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/PDFUpload.do")
	public void uploadPDF(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");
		if (ServletFileUpload.isMultipartContent(request)) {
			DiskFileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setHeaderEncoding("UTF-8");
			//create an new progress listener of uploading.
			FileUploadProgressListener progressListener = new FileUploadProgressListener(request);
			upload.setProgressListener(progressListener);
			List<FileItem> items = new ArrayList<FileItem>();
			HashMap<String,String> map = new HashMap<String, String>();
			try {
				items = upload.parseRequest(request);
			} catch (FileUploadException e) {
				logger.error("UploadFileFailed",e);
				this.setErrorResponse(response, "UploadFileFailed");				
			}
			
			for (FileItem fileItem : items) {
				if (!fileItem.isFormField()) {
					this.uploadFile = fileItem;
				} else {
					// get name of simple field 
					String fieldName = fileItem.getFieldName();
					// get value of simple field.
					String fieldValue = fileItem.getString("UTF-8");
					request.setAttribute(fieldName, fieldValue);
				}
			}
			this.servletRequest = request;	
			if (this.uploadFile != null){
				String userId = Config.FOXIT_USER_ID_KEY;
				FoxitCloudUtils utils = new FoxitCloudUtils();
				InputStream in = this.uploadFile.getInputStream();
				String fileName = this.uploadFile.getName();
				if(utils.saveUploadedFile(userId, map, in, fileName)){
					byte[] bytes = null;      
			        ByteArrayOutputStream bos = new ByteArrayOutputStream();      
			        try {        
//					Convert2BinTask covertTask = new Convert2BinTask(map.get("docId"), data, fileName);
//					covertTask.run();
				    TaskStore taskStore = new TaskStore();
				    taskStore.pushTask((String)map.get("docId"), bytes, fileName,(String)map.get("token"));
				    //taskStore.getTaskStatus((String)map.get("docId"));
				    FoxitCloudUtils.setErrorResponse(response,map);
				    
			        } catch (IOException ex) {        
			            ex.printStackTrace();  
			            FoxitCloudUtils.setErrorResponse(response,map);
			        }  
				}else{
					FoxitCloudUtils.setErrorResponse(response,map);
				}
			}
		} else {
			logger.error("UploadFileFailed");
		}
	}




	
	private void setErrorResponse(HttpServletResponse response,String errorInfo) throws IOException
	{
		HashMap<String, String> hashMap = new HashMap<String, String>();
		hashMap.put("errorInfo", errorInfo);
		Gson gson = new Gson();
		response.getWriter().write(gson.toJson(hashMap).toString());
	}
	
	
	
}
